package com.notebad.ui;

import java.io.File;
import java.io.IOException;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.media.MediaRecorder;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.os.SystemClock;
import android.preference.PreferenceManager;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ImageButton;
import android.widget.TextView;

import com.notebad.R;
import com.notebad.note.DataBaseAdapter;
import com.notebad.note.Note;

public class AudioRecorderView extends Activity implements OnClickListener {

	private static final String TAG = "[AudioRecorderView]";
	private ImageButton recordButton;
	private ImageButton stopButton;
	private TextView timer;
	private updateThread thread;
	private long startTime = 0;
	private boolean fromMenu = false;

	private final MediaRecorder recorder = new MediaRecorder();
	private String path= Note.getCurrentNote().getSoundsFolder() + "/" + "son-"+(Note.getCurrentNote().getMaxIndexSound() + 1);

	Handler handler = new Handler()
	{
		public void handleMessage(Message msg) 
		{
			startTime = startTime + 1000;
			timer.setText(convertTime(startTime));
		}
	};
	
	public void onCreate(Bundle savedInstanceState) 
	{
		super.onCreate(savedInstanceState);

		setContentView(R.layout.audio_recorder);		

		recordButton = (ImageButton) findViewById(R.id.Record);
		recordButton.setOnClickListener(this);

		stopButton = (ImageButton) findViewById(R.id.Stop);
		stopButton.setOnClickListener(this);
		stopButton.setEnabled(false);
		
		timer = (TextView) findViewById(R.id.Time);

		Bundle param = this.getIntent().getExtras();
	    if(param != null)
	    {
	    	fromMenu = param.getBoolean("fromMenu");
	    }
	}

	protected void onStop() 
	{
		super.onStop();

		if(thread != null)
		{
			thread.stop();
		}
		recorder.release();
	}

	@Override
	public void onClick(View view) 
	{
		switch(view.getId()) 
		{
		case R.id.Record:
			try 
			{
				this.record();
			} 
			catch (IllegalStateException e) 
			{
				// TODO Auto-generated catch block
				e.printStackTrace();
			} 
			catch (IOException e) 
			{
				e.printStackTrace();
			}
			return;

		case R.id.Stop:
			this.stop();
			return;
		}
	}

	/**
	 * Starts a new recording.
	 * @throws IOException 
	 * @throws IllegalStateException 
	 */
	private void record() throws IllegalStateException, IOException
	{
		SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(AudioRecorderView.this);
		String format = prefs.getString(AudioRecorderView.this.getResources().getString(R.string.pref_def_sound_format), "3GP");
		
		recorder.reset();
		recorder.setAudioSource(MediaRecorder.AudioSource.MIC);
		if(format.compareTo("3GP") == 0)
		{
			path = path + "." + format;
			recorder.setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP);
		}
		else if(format.compareTo("MPEG4") == 0)
		{
			path = path + "." + format;
			recorder.setOutputFormat(MediaRecorder.OutputFormat.MPEG_4);
		}
		recorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB);
		recorder.setOutputFile(path);
		recorder.prepare();
		recorder.start();
		
		thread = new updateThread();
		startTime= 0;
		thread.start();
		stopButton.setEnabled(true);
		recordButton.setEnabled(false);
	}

	/**
	 * Stops a recording that has been previously started.
	 */
	private void stop()
	{
		recorder.stop();
		thread.stop();
		stopButton.setEnabled(false);
		recordButton.setEnabled(true);

		AlertDialog.Builder builder = new AlertDialog.Builder(AudioRecorderView.this);
		builder.setMessage("Enregistrer le son ?")
		.setCancelable(false)
		.setPositiveButton("Oui", new DialogInterface.OnClickListener() {
			public void onClick(DialogInterface dialog, int id) {
				//save sound

				if(Note.getCurrentNote()==null){
				}

				Note.getCurrentNote().incrementIndexSound();

				if(!Note.getCurrentNote().isNew()){
					DataBaseAdapter manager = new DataBaseAdapter(AudioRecorderView.this);
					manager.open();
					manager.updateNote(Note.getCurrentNote());
					manager.close();
				}
				if(fromMenu)
				{
					Intent intent = new Intent(AudioRecorderView.this, VisualisationView.class);
					intent.putExtra("tab", 2);
					startActivity(intent);
				}
				finish();
			}
		})
		.setNegativeButton("Non", new DialogInterface.OnClickListener() {
			public void onClick(DialogInterface dialog, int id) {
				// Delete the file on the sdcard
				new File(path).delete();
				startTime = 0;
				timer.setText(convertTime(startTime));
				dialog.cancel();
				onResume();
			}
		});
		AlertDialog alert = builder.create();
		alert.show();
	}
	
	private class updateThread implements Runnable {

		private volatile Thread blinker;

		public void start() 
		{
			blinker = new Thread(this);
			blinker.start();
		}

		public void stop() 
		{
			blinker = null;
		}

		public void run() 
		{
			Thread thisThread = Thread.currentThread();
			startTime= SystemClock.currentThreadTimeMillis();
			while (blinker == thisThread) 
			{
				try
				{
					handler.sendMessage(handler.obtainMessage());
					Thread.sleep(1000);
				}
				catch(InterruptedException e)
				{
					Log.e(TAG, e.getMessage());
				}
			}
		}
	}
	
	private String convertTime(long time)
	{
	    String format = String.format("%%0%dd", 2);  
	    time = time / 1000;  
	    String seconds = String.format(format, time % 60);  
	    String minutes = String.format(format, (time % 3600) / 60);  
	    String hours = String.format(format, time / 3600);
	    
	    String result = "";
	    if(hours.compareTo("00") == 0)
	    {
	    	result = minutes + ":" + seconds;
	    }
	    else
	    {
	    	result =  hours + ":" + minutes + ":" + seconds; 
	    }
	    return result; 
	}
}
